//
//  HYFStatusDAL.swift
//  MyWeibo
//
//  Created by 黄勇锋 on 16/8/1.
//  Copyright © 2016年 黄勇锋. All rights reserved.
//

import UIKit

class HYFStatusDAL: NSObject {

    /*
     01 - 查询数据 -> 返回数据
     - 如果查询本地有数据  直接返回
     - 如果查询本地没有数据
     - 网络请求数据
     - 保存数据
     02 - 保存数据
     03 - 删除数据
     */
    // 查询微博数据
    
    //检查本地是否有数据
    class func checkCache(sinceId:Int64,maxId:Int64,callback:(response:[[String:AnyObject]]?)->()){
        
        //本地查询到的数据
        let result = HYFStatusDAL.getCache(sinceId, maxId: maxId)
        //代表本地有缓存数据
        if result?.count > 0 {
            print("本地数据")
            callback(response: result)
        }else{
            //本地没有缓存
            print("网络数据")
            HYFNetworkTools.shardTools.homeLoadData(sinceId, maxId: maxId, success: { (response) in
                //判断是否为nil 而且是否可以转成数组
                guard let res = response?["statuses"] as? [[String:AnyObject]] else{
                    
                    callback(response: nil)
                    return
                }
                
                callback(response: res)
                //保存数据
                HYFStatusDAL.saveCache(res)
                
                }, failure: { (error) in
                    
                  print("请求数据失败:\(error)")
                  callback(response: nil)
            })
        }
    }
    
    // 类方法
    class func getCache(sinceId:Int64,maxId:Int64) ->[[String:AnyObject]]?{
        
        //判断用户 uid 是否存在
        guard let userId = HYFUserAccountViewModel.sharedTools.userAccount?.uid else{
            
            print("用户没有登录")
            return nil
        }
       //准备 sql
        var sql = ""
        sql += "SELECT * FROM T_SHStatus\n"
        sql += "WHERE userid = \(userId)\n"
        
        if sinceId > 0 {
            
            sql += "AND statusid>\(sinceId)\n"
        }
        
        if maxId > 0 {
            
            sql += "AND statusid<=\(maxId)\n"
        }
        
        sql += "ORDER BY statusid DESC\n"
        sql += "LIMIT 20"
        
        //得到查询结果
        let result = SHSQLManager.sharedTools.selectRecord(sql)
        //创建一个临时数组
        var tempArray:[[String:AnyObject]] = [[String:AnyObject]]()
        //遍历数组
        for dic in result{
            
            let dict = try! NSJSONSerialization.JSONObjectWithData(dic["status"] as! NSData, options: []) as! [String : AnyObject]
            //保存字典
            tempArray.append(dict)
        }
        return tempArray
    }
    
    
    //保存微博数据
    class func saveCache(response:[[String:AnyObject]]){
        
        //用户 uid
        guard let userId = HYFUserAccountViewModel.sharedTools.userAccount?.uid else{
            
            print("用户没有登录")
            return
        }
        
        //准确 sql
        let sql = "INSERT OR REPLACR INTO T_SHStatus (statusid,userid,status) VALUES(?,?,?)"
        //执行 sql
        SHSQLManager.sharedTools.queue.inTransaction { (db, rollback) in
            
            //遍历数组
            for dic in response{
                
                //微博 id
                let statusId = dic["id"] as! NSNumber
                //微博数据
                let status = try!NSJSONSerialization.dataWithJSONObject(dic, options: [])
                let result = db.executeQuery(sql, withArgumentsInArray: [statusId,userId,status])
                
                if (result != nil){
                    
                    print("保存数据成功")
                }else{
                    
                    print("保存数据失败")
                    rollback.memory = true
                }
            }
        }
    }
    
    //删除本地微博数据
    class func deleteCache(){
        
        //日期
        let timeStr = NSDate.sinaDeleteTimeStr()
        //准备 sql
        let sql = "DELETE FROM T_SHStatus WHERE createtime<'\(timeStr)'"
        //执行 sql 
        SHSQLManager.sharedTools.queue.inDatabase { (db) in
            
            let result = db.executeUpdate(sql, withArgumentsInArray: nil)
            
            if result{
                
                print("删除数据成功")
            }else{
                
                print("删除数据失败")
            }
        }
    }
}
